//app.js
var handler = require("utils/function.js");
// 8.23新增---------------------------------------------
let  QQMapWX = require("utils/qqmap-wx.js");
var demo = new QQMapWX({
  key: 'EKJBZ-72L3P-FHXDL-VSLEP-JEAGJ-JTFSD' // 必填
});
var siteinfo = require("siteinfo.js");
var rqurl = siteinfo.siteroot.replace("app/index.php", "api.php?s=");
// 8.23新增---------------------------------------------
// 播放器
const innerAudioContext = wx.createInnerAudioContext();
innerAudioContext.obeyMuteSwitch = false;
var timeWaitCount; //司机等待时间定时器


/**
 * 录音播放
 * @param src 音频地址
 * @param duration 音频秒数（单位 S）
 */
let SoundRecordingPlay = function ({ src, duration }) {
  let _src = src;
  let _duration = duration;
  if (_src && _duration) {
    innerAudioContext.src = _src
    innerAudioContext.play();
    // setTimeout(function () {
    //   innerAudioContext.stop();
    // }, _duration * 1000)
  }
}
var socketOpen = false
var socketMsgQueue = []
App({
  test:1,       //0:测试版  1:正式版
  driver_position: [
    { latitude: '', longitude: '' }
  ],
  actual_km: '',
  actual_km_price: '',
  timer: null,
  latitude: '',
  longitude: '',
  img: "/images/user/",
  city: '',
  api: require("api.js"),
  siteInfo: require("siteinfo.js"),
  user_location: {},
  webRoot: null,
  currentPage: null,
  is_binding: 0,
  shareInfo: {},
  wait_time: 0,
  get_order: 0,
  like: 1,//订单模式
  driver_url: 0,
  postlist: [],//获取代驾人员位置
  longitudes:'',
  latitudes:'',
  navTo(e){
    wx.navigateTo({
      url: e,
    })
  },
  showToast(txt, i, speed, code) {
    wx.showToast({
      title: txt, icon: i == 1 ? 'success' : 'none', mask: true, duration: speed ? speed : 1500, success: () => {
        setTimeout(() => {
          code ? code() : 0
        }, speed ? speed : 0)
      }
    })
  },
  reverseGeocoder(o){
    demo.reverseGeocoder({
      location: {
        latitude: o.lat,
        longitude: o.lng
      },
      get_poi:1,
      success(res){
        o.success(res)
        // console.log(res)
        //return res
      }
    })
  },
  setApi: function () {
    var o = this.siteInfo.siteroot;
    o = o.replace("app/index.php", ""), o += "api.php/?s=",
      this.api = function t(e) {
        for (var a in e) "string" == typeof e[a] ? e[a] = e[a].replace("{$_api_root}", o) : e[a] = t(e[a]);
        return e;
      }(this.api);
    var t = this.api.default.index,
      e = t.substr(0, t.indexOf("/api.php"));
    this.webRoot = e;
  },
  onhidesocket(){
    let that = this;
    var urls = this.siteInfo.siteroot;
    urls = urls.replace("/app/index.php", "");
    urls = urls.replace("https", "wss");
    // console.log(urls)
    wx.connectSocket({
      url: urls
    })
    //监听WebSocket错误
    wx.onSocketError(function (res) {
      socketOpen = false
      console.log('WebSocket连接打开失败，请检查！')
    })
    //监听WebSocket连接打开事件。
    wx.onSocketOpen(function (res) {
      console.log('WebSocket连接打开')
      socketOpen = true
      var arr = {};
      arr.type = "login";
      arr.client_name = wx.getStorageSync("access_token");
      arr.room_id = that.siteInfo.acid;
      arr.uid = wx.getStorageSync("access_token");;
      wx.sendSocketMessage({
        data: JSON.stringify(arr),
      })
    })
  },
  // 定时器获取当前位置
  startReportHeart: function (order_no) {
    let that = this;
    let timer = this.timer;
    var synamicdata = {};
    synamicdata.type = 'driver_position';
    synamicdata.order_no = order_no;
    that.timer = setInterval(function (){
      wx.getLocation({
        altitude:true,
        type: 'gcj02',
        success: function (res) { 
          that.longitudes = res.longitude;
          that.latitudes=res.latitude;
          synamicdata.lat = res.latitude;
          synamicdata.lng = res.longitude;
          wx.sendSocketMessage({
            data: JSON.stringify(synamicdata),
          })
          socketOpen = true;
        },
      })
    }, 5000)
  },
  //抢单后 实时上报司机位置
  uploadLocation:function (order_no) {
    let that = this;
    let timer = this.timer;
    console.log("派单模式")
    var synamicdata = {};
    synamicdata.type = 'driverToStart_position';
    synamicdata.order_no = order_no;
    that.timer = setInterval(function () {
      wx.getLocation({
        altitude: true,
        type: 'gcj02',
        success: function (res) {
          synamicdata.lat = res.latitude;
          synamicdata.lng = res.longitude;
          // console.log("正在上报司机位置", synamicdata);
          wx.sendSocketMessage({
            data: JSON.stringify(synamicdata),
          })
          socketOpen = true;
        },
      })
    }, 5000)
  },
  //用户下单后 上传服务端订单编号
  uploadOrder: function (order_no) {
    let that = this;
    let timer = this.timer;
    var synamicdata = {};
    synamicdata.type = 'getOrder_status';
    synamicdata.order_no = order_no;
    console.log("商法订单")
    wx.sendSocketMessage({
      data: JSON.stringify(synamicdata),
    })
  },
  // 结束定时器
  endReportHeart: function () {
    clearInterval(this.timer);
  },

  // 开启司机等待倒计时
  waitTime () {
    let time = wx.getStorageSync('timeWait') || 0;
    timeWaitCount = setInterval(() => {
      wx.setStorageSync("timeWait", time++)
    }, 1000);
  },
  //结束司机等待倒计时
  endWaitTime () {
    clearInterval(timeWaitCount);
    wx.setStorageSync("timeWait", '');
  },
  onHide:function(){
    console.log("小程序关闭")
    let that = this;
    var i = 0;
    wx.startLocationUpdateBackground({
      success(res) {
        // console.log(res)
        //setInterval(() => {
          wx.onLocationChange(function (rese) {
            i++;
            // console.log(i,'------------------------i')
            if(i%5==0){
              that.Request({
                url: 'real_time/add', method: 'post', data: {
                  lat: rese.latitude,
                  lng: rese.longitude
                },
              }).then((res) => {
                if (res.code == 1) {

                } else {

                }
              })
            }
            // console.log('location change', rese)
            //that.onhidesocket()
          })
        //}, 2000)
      },
      fail(err) {
        console.log(err)
      }
    })
  },
  onLaunch: function () {
    this.setApi();
    this.updateEdi();
    // this.getUserInfo();
    // this.getlocation()
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo
              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
        // console.log(res.authSetting['scope.userLocationBackground'])
        if (res.authSetting['scope.userLocationBackground']){
          // console.log(res.authSetting['scope.userLocationBackground'])
        }
      }
    })
    var that = this;
    //获取优惠券数据
    this.getShare()
    //循环间隔 单位ms
    setInterval(function () {
      that.getdlocation();

    }, 10000)

  },

  updateEdi() {
    const updateManager = wx.getUpdateManager()
          updateManager.onCheckForUpdate(function (res) {
            // 请求完新版本信息的回调
            console.log(res.hasUpdate)
          })
          updateManager.onUpdateReady(function () {
            wx.showModal({
              title: '更新提示',
              content: '新版本已经准备好，是否重启应用？',
              success: function (res) {
                if (res.confirm) {
                  // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                  updateManager.applyUpdate()
                }
              }
            })
          })
          updateManager.onUpdateFailed(function () {
            // 新版本下载失败
            wx.showModal({
              title: '提示',
              content: '下载新版本失败，请删除小程序后重新进入',
              showCancel: 'false'
            })
          })
  },
  getUserInfo: function (cb) {
    wx.getUserInfo({
      success: res => {
        // 登录
        wx.login({
          success: re => {
            // 发送 res.code 到后台换取 openId, sessionKey, unionId
            this.request({
              url: this.api.user.login,
              method: 'post',
              data: {
                code: re.code,
                iv: res.iv,
                encryptedData: res.encryptedData
              },
              success: function (rs) {
                //获取到用户详细信息
                if (rs.code == 1) {
                  this.is_binding = rs.data.is_binding;
                  wx.setStorageSync("access_token", rs.data.access_token);
                  wx.setStorageSync("serverphone", rs.data.serverphone);

                  if (rs.data.type == 1 && rs.data.audit == 1 && rs.data.status == 1) {
                    wx.reLaunch({
                      url: '../../index/index'
                    })
                  }
                  //保存数据 用来判断是否绑定手机号
                  wx.setStorageSync('is_binding', rs.data.is_binding)
                }
              }
            })

          }
        })
      }
    })
  },
  // 获取用户的地理位置
  getlocation: function () {
    // console.log(cb)
    const that = this;
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        var latitude = res.latitude
        var longitude = res.longitude
        var speed = res.speed
        var accuracy = res.accuracy
        var locationString = res.latitude + "," + res.longitude; //获取的经度纬度
        wx.request({
          url: 'https://apis.map.qq.com/ws/geocoder/v1/?l&get_poi=1', //根据经纬度转换成具体地址
          data: {
            "key": "YLFBZ-WHAWI-ZXUGH-53Q65-TOJ7E-ADBNQ",
            "location": locationString
          },
          method: 'GET',
          // header: {},
          success: function (res) {
            wx.setStorageSync("startAddress", {
              title: res.data.result.address,
              address: res.data.result.address,
              location: {
                lat: latitude,
                lng: longitude
              }
            });
            if (wx.getStorageSync("userMessage") != '') {
              that.request({
                url: that.api.real_time.add,
                method: 'post',
                data: {
                  lat: latitude,
                  lng: longitude
                },
                success: function (rs) {
                  wx.setStorageSync("positioning", rs.data);
                }
              })
            }
          },
          fail: function () {
            // fail
            that.getlocation()
            // console.log("请求失败");
          },
          complete: function (rs) {
            // complete
            // console.log("请求完成", rs);
          }
        })
      }
    })
  },
  getdlocation: function () {
    let that = this;
    if (wx.getStorageSync("access_token") != '' && wx.getStorageSync("usertype") == 1) {
      wx.getLocation({
        type: 'gcj02',
        success: function (res) {
          var latitude = res.latitude
          var longitude = res.longitude
          that.posting(latitude, longitude);
          // var speed = res.speed
          // var accuracy = res.accuracy
          // var locationString = res.latitude + "," + res.longitude; //获取的经度纬度
          // that.request({
          //     url: that.api.real_time.add,
          //     method: 'post',
          //     data: {
          //         lat: latitude,
          //         lng: longitude
          //     },
          //     success: function(rs) {
          //       if (rs.data.message!=0)
          //       wx.setStorageSync("get_order", rs.data.message)
          //       if (rs.data.type==1){
          //         if (rs.data.new_order==1){
          //           new SoundRecordingPlay({ src: '/we7/resource/video/alert.mp3', duration: "14" });
          //         }
          //       }
          //         wx.setStorageSync("positioning", rs.data);
          //     }
          // })
        }
      })
    }
  },
  // 路线规划
  routeLPlan: function (start, end) {
    var arr = [];
    demo.direction({
      mode: 'driving',//可选值：'driving'（驾车）、'walking'（步行）、'bicycling'（骑行），不填默认：'driving',可不填
      //from参数不填默认当前地址
      from: start,
      to: end,
      success: function (res) {
        // console.log("app.js",res.result.routes);
        var ret = res;
        var coors = ret.result.routes[0].polyline, pl = [];
        //坐标解压（返回的点串坐标，通过前向差分进行压缩）
        var kr = 1000000;
        for (var i = 2; i < coors.length; i++) {
          coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
        }
        //将解压后的坐标放入点串数组pl中
        for (var i = 0; i < coors.length; i += 2) {
          arr.push({ latitude: coors[i], longitude: coors[i + 1] })
        }
        // console.log(pl)
        //设置polyline属性，将路线显示出来,将解压坐标第一个数据作为起点
      },
      fail: function (error) {
        console.error(error);
      },
      complete: function (res) {
      }
    });
    return arr;
  },
  Request: function (o) {
    let that = this;
    o.data ? o.data : o.data = {};
    var t = wx.getStorageSync("access_token");
    o.data.access_token = t;
    o.data._uniacid = that.siteInfo.uniacid;
    o.data._acid = that.siteInfo.acid;
    return new Promise((resolve, reject) => {
      wx.request({
        url: rqurl + o.url, data: o.data, method: o.method,
        header: {
          // "content-type": "application/x-www-form-urlencoded",
          // "content-type": 'text/json'
        },
        success: function (response) {
          if (response.data.code == -100) {
            wx.showModal({
              title: '提示',
              content: '小程序应用未注册，请联系开发者',
              showCancel: false
            })
          } else if (response.data.code == -1) {
            that.navTo('/pages/logs/logs')
            // wx.showToast({
            //   title: response.data.msg,
            //   icon: 'none',
            // })
          }
          resolve(response.data)
        },
        error: (error) => {
          reject(error)
        }
      })
    })
  },
  request: function (a) {
    a.data || (a.data = {});
    var t = wx.getStorageSync("access_token");
    t && (a.data.access_token = t), a.data._uniacid = this.siteInfo.uniacid, a.data._acid = this.siteInfo.acid,
      wx.request({
        url: a.url,
        header: a.header || {
          "content-type": "application/x-www-form-urlencoded"
        },
        data: a.data || {},
        method: a.method || "GET",
        dataType: a.dataType || "json",
        success: function (t) {
          if (t.data.code == -100) {
            wx.showModal({
              title: '提示',
              content: '小程序应用未注册，请联系开发者',
              showCancel: false
            })
          } else if (t.data.cod == -1){
            that.navTo('/pages/logs/logs')
          }else{
            a.success && a.success(t.data);
          }
           //- 1 == t.data.code ? '' : a.success && a.success(t.data);
        },
        fail: function (t) {
          // console.warn("--- request fail >>>"), console.warn(t), console.warn("<<< request fail ---");
          var e = getApp();
          e.is_on_launch ? (e.is_on_launch = !1, wx.showModal({
            title: "",
            content: t.errMsg,
            showCancel: !1,
            success: function (t) {
              t.confirm && a.fail && a.fail(t);
            }
          })) : ('', a.fail && a.fail(t));
        },
        complete: function (t) {
            console.log(t)
          200 != t.statusCode && (console.log("--- request http error >>>"), console.log(t.statusCode), console.log(t.data), console.log("<<< request http error ---")), a.complete && a.complete(t);
        }
      });
  },
  globalData: {
    userInfo: null
  },
  // 获取转发参数
  getShare: function () {
    let that = this;
    this.request({
      url: this.api.share.index,
      method: 'post',
      data: {
      },
      success: function (rs) {
        // console.log(rs)
        if (rs.code == 1) {
          wx.setNavigationBarTitle({
            title: rs.data.title
          })
          that.shareInfo = rs.data;
          wx.setStorageSync("mp3", rs.data.videomp3)
          // rs.data.usertype&&wx.setStorageSync("usertype", rs.data.usertype)
          // that.setData({ shareInfo:rs.data })
        } else {

          wx.showToast({
            title: rs.msg,
          })
        }
        // shareInfo
      }
    })
  },
  //分享优惠券
  shareCouponsMessage: function (e) {
    let that = this;
    // 转发获取用户uid
    this.request({
      url: this.api.share.coupons,
      method: 'post',
      data: {
        uid: e
      },
      success: function (rs) {
        // wx.showToast({
        //   title: wx.getStorageSync("uid"),
        // })
        if (rs.code == 1) {
        } else {
          // wx.showToast({
          //   title: rs.msg,
          // })
        }
        // shareInfo
      }
    })

  },
  //转发参数
  shareAppMessage: function (e) {
    return {
      title: this.shareInfo.title,
      imageUrl: this.shareInfo.image,
      desc: this.shareInfo.desc,
      path: '/pages/map/driverServer/driverServer?uid=' + wx.getStorageSync("uid")
    }
  },
  // 获取位置
  posting: function (lat, lng) {
    //room_id positioning

    var that = this;
    // console.log('调取函数')
    var toke = wx.getStorageSync("access_token");
    var arr1 = {};

    arr1.type = 'positioning';
    arr1.room_id = that.siteInfo.acid;
    arr1.lat = lat;
    arr1.lng = lng;
    arr1.token = toke;
    // arr1.type = 'driver';
    // arr1.room_id = '9';
    // console.log(arr1,'');
    wx.sendSocketMessage({
      data: JSON.stringify(arr1),
    })
    socketOpen = true;
  },
  // 长连接
  gateway: function (order_no, status, deletesay) {
    var arr1 = {};
    arr1.type = 'say';
    arr1.order_no = order_no;
    arr1.status = status;
    arr1.deletesay = deletesay;
    // console.log('我以获取参数scj',arr1)
    wx.sendSocketMessage({
      data: JSON.stringify(arr1),
    })
    socketOpen = true;

  },
  driver: function () {
    var that = this;
    // console.log('调取函数')
    var arr1 = {};
    arr1.type = 'driver';
    arr1.client_name = wx.getStorageSync("access_token");;
    arr1.room_id = that.siteInfo.acid;
    // arr1.type = 'driver';
    // arr1.room_id = '9';
    // console.log(arr1);
    wx.sendSocketMessage({
      data: JSON.stringify(arr1),
    })
    socketOpen = true;
  },
  onShow: function (e) {
    wx.stopLocationUpdate({
      success(res) {
        console.log(res)
        console.log('关闭i成功')
      }
    })
    let that = this;
    that.forever_realtive();
    // this.getShare()
    wx.setKeepScreenOn({
      keepScreenOn: true
    })
  },
  // 常连接函数
  forever_realtive: function () {
    var that = this;
    // wx.closeSocket();
    var urls = this.siteInfo.siteroot;
    urls = urls.replace("/app/index.php", "");
    urls = urls.replace("https", "wss");
    console.log(urls)
    wx.connectSocket({
      url: urls
    })
    //监听WebSocket错误
    wx.onSocketError(function (res) {
      socketOpen = false
      console.log('WebSocket连接打开失败，请检查！')
    })
    //监听WebSocket连接打开事件。
    wx.onSocketOpen(function (res) {
      console.log('WebSocket连接打开')
      socketOpen = true
      var arr = {};
      arr.type = "login";
      arr.client_name = wx.getStorageSync("access_token");
      arr.room_id = that.siteInfo.acid;
      arr.uid = wx.getStorageSync("access_token");;
      wx.sendSocketMessage({
        data: JSON.stringify(arr),
      })
    })
    //监听WebSocket接受到服务器的消息事件
    wx.onSocketMessage(function (res) {
      // console.log('返回参数 回调scj', res)
      // console.log("长连接返回值", res)
      var data = JSON.parse(res.data);
      // console.log('最新测试',data);
      switch (data['type']) {
        // 服务端ping客户端
        case 'ping':
          var arr = {};
          arr.type = "pong";
          wx.sendSocketMessage({
            data: JSON.stringify(arr),
          })
          break;
        // 登录 更新用户列表
        case 'login':
          socketOpen = true
          break;
        case 'driver_position':
          // console.log('收到driver_position消息', data)
          let points = JSON.parse(data.data.position_point);
          let pointsEnd = JSON.parse(data.data.target_adds_location);
          console.log(pointsEnd);
// 测试显示实时价格和路程
          that.actual_km = data.data.actual_km
          that.actual_km_price = data.data.actual_km_price
          
          that.driver_position = that.routeLPlan(points[points.length - 1], { latitude: pointsEnd.lat, longitude: pointsEnd.lng});
          socketOpen = true
          break;
        case 'driver':
          // console.log('退缩美好消息2driver')
          if (data['status'] == 1 && wx.getStorageSync("usertype") == 1) {
            // console.log('driver-----------')
            
            new SoundRecordingPlay({
              src: wx.getStorageSync("mp3"),
              duration: "14"
            });
          }
          socketOpen = true
          break;
		case 'driver_task':
			that.uploadLocation(data['order_no']);
			new SoundRecordingPlay({
			  src: wx.getStorageSync("mp3"),
			  duration: "14"
			});
			socketOpen = true
			break;
        case 'say':
          // console.log('收到消息driver', data)
          if (data['status'] == 1) {
            wx.redirectTo({
              url: '/pages/map/getOrderNotGoing/getOrderNotGoing?order_no=' + data['order_no'],
            })
          } else if (data['status'] == 2) {
            //跳转到进行中页面
            wx.redirectTo({
              url: '/pages/map/orderGoing/orderGoing?order_no=' + data['order_no'],
            })
          } else if (data['status'] == 3) {
            //跳转到待付款页面
            wx.redirectTo({
              url: '/pages/pay/paidOrder/paidOrder?order_no=' + data['order_no'],
            })
          } else if (data['status'] == 4) {
            //跳转到待付款页面
            wx.redirectTo({
              url: '/pages/userOrder/orderDetail/orderDetail?order_no=' + data['order_no'],
            })
          } else if (data['status'] == 5) {
            console.log(data['deletesay'], '22222222222222222222222')
            //跳转到首页
            setTimeout(() => {
              wx.reLaunch({
                url: '/pages/map/driverServer/driverServer?deleteOrder=true',
              })
            }, 1500)
          }
          socketOpen = true
          break;
        case 'positioning':
          // console.log('收到消息positioning', data)
          var arrx = [];
          that.postlist['' + data.token + ''] = [data.positioning.lat, data.positioning.lng];
          // console.log('收到消息positioning222', postlist)
          socketOpen = true
          break;
        case 'driverToStart_position':
          // 用户端获取司机实时位置
          wx.setStorageSync('driver_now_position', data)
          if(data['data'].is_service == 4) {
            that.endReportHeart();
          }
          break;
      }
    })
    //监听WebSocket关闭
    wx.onSocketClose(function (res) {
      socketOpen = false
      // console.log(' 已关闭！')
    })
  },
  // 收集formID
  PushfromId: function (res) {
    var formid = res;
    if (formid) {
      this.request({
        url: this.api.share.getformid,
        method: 'post',
        data: {
          formid: formid
        },
        success: function (rs) {
          if (rs.code == 1) {
          } else {
          }
        }
      })
    }
  },

})